<?php

class WorkflowController extends Controller
{
   
    public $menu = array(
        array(
            'label' =>  '工作流',
        ),
        array(
            'label' =>  '工作流列表',
            'icon'  =>  'leaf',
            'url'   =>  array('/workflow/index'),
        ),
        array(
            'label' =>  '新建工作流',
            'icon'  =>  'plus',
            'url'   =>  array('/workflow/create'),
        ),
    );
    
    /**
     * @return array action filters
     * 
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/workflow/index.php'
        $model=new Workflow;
        if(isset($_GET['Workflow'])) {
            $model->attributes=$_GET['Workflow'];
        }
		
        $sql = 'select * from (select * from workflow order by workflow_id DESC, workflow_version DESC) t group by workflow_name';
        $sqlCount = 'select count(*) from (select * from workflow order by workflow_id DESC, workflow_version DESC) t group by workflow_name';
		if(isset($_GET['id'])) {
            $sql = 'select * from (select * from workflow order by workflow_id DESC, workflow_version DESC) t group by workflow_name having workflow_name=\''.$_GET['id'].'\'';
             $sqlCount = 'select count(*) from (select * from workflow order by workflow_id DESC, workflow_version DESC) t group by workflow_name having workflow_name=\''.$_GET['id'].'\'';
        }
        $count=Yii::app()->db->createCommand($sqlCount)->queryScalar();
        $dataProvider=new CSqlDataProvider($sql, array(
        	'id'=>'user',
            'totalItemCount'=>$count,
            'pagination'=>array(
            	'pageSize'=>20,
            ),
		));
        
        $this->render('index', array(
            'dataProvider'  => $dataProvider,
            'model'         => $model,
        ));        
    } 

    public function actionCreate() {
        $workflow = new Workflow;
        
   		if(isset($_POST['Workflow']))
        {
        	$workflow->attributes = $_POST['Workflow'];
        	$workflow->workflow_version = 1;
            if(WorkflowUtil::saveWorkflow($workflow, $_POST['Workflow']['xml'])) {
                $this->redirect(array('index'));
            }
        }
        $this->render('xml', array(
            'flow'  =>  $workflow,
        ));
    }

    public function actionUpdate($id) {

        $workflow = Workflow::model()->findByPk($id);
    	if(isset($_POST['Workflow']))
        {
            if(WorkflowUtil::saveWorkflow($workflow, $_POST['Workflow']['xml'])) {
                $this->redirect(array('index'));
            }
        }
        $this->render('xml', array(
            'flow'   =>  $workflow,
        ));
    }

    public function actionGraph() {
    	if(isset($_GET['id'])) {
            $workflows = array(Workflow::model()->findByPk($_GET['id']));
        }
        else {
            $workflows = Workflow::model()->findAll();
        }
        $this->render('graph', array(
            'flows'  => $workflows,
        ));
    }

    public function actionText()
    {
        if(isset($_GET['id'])) {
            $workflows = array(Workflow::model()->findByPk($_GET['id']));
        }
        else {
            $workflows = Workflow::model()->findAll();
        }
        $this->render('text', array(
            'flows'  => $workflows,
        ));
    }

    public function actionNode()
    {
    	$criteria = new CDbCriteria;

        if(isset($_GET['id'])) {
            $criteria->addCondition('workflow_id='.$_GET['id']);
        }
        $dataProvider = new CActiveDataProvider('WorkflowNode', array(
            'pagination'    =>  array(
                'pageSize'  =>  20,
            ),
            'criteria'  =>  $criteria,
        ));
        $this->render('node', array(
            'dataProvider'  => $dataProvider,
        ));
    }

    public function actionVariable()
    {
        $criteria = new CDbCriteria;

        if(isset($_GET['id'])) {
            $criteria->addCondition('workflow_id='.$_GET['id']);
        }
        $dataProvider = new CActiveDataProvider('WorkflowVariables', array(
            'pagination'    =>  array(
                'pageSize'  =>  20,
            ),
            'criteria'  =>  $criteria,
        ));
        $this->render('variable', array(
            'dataProvider'  => $dataProvider,
        ));
    }

    public function actionImage($name) 
    {
        $jpgPath = Yii::app()->runtimePath . "/{$name}.jpg";
        echo file_get_contents($jpgPath);
    }
    
	public function actionDelete()
    {
        if(Yii::app()->request->isPostRequest)
        {
			WorkflowService::getInstance()->deleteByName($_GET['id']);
			Yii::log("workflow[{$_GET['id']}] was deleted successfully", CLogger::LEVEL_INFO, FRONTEND_LOG);
            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_GET['ajax']))
                $this->redirect(array('index'));
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    public function actionAjaxDelete()
    {
        $autoIdAll = $_POST['autoId'];

        foreach ($autoIdAll as $autoId) {
        	WorkflowService::getInstance()->deleteById($autoId);
        	Yii::log("workflow[$autoId] was deleted successfully", CLogger::LEVEL_INFO, FRONTEND_LOG);
        }
    }
}
